// 定义 Logger 类
class Logger {
    constructor() {
        this.logQueue = [];
        this.maxLogs = 1000; // 最大保存日志数量
        this.logFile = 'logs.txt'; // 日志文件名
        
        // 从本地存储恢复日志
        try {
            const savedLogs = localStorage.getItem('appLogs');
            if (savedLogs) {
                this.logQueue = JSON.parse(savedLogs);
            }
        } catch (e) {
            console.error('无法从本地存储恢复日志:', e);
        }
    }

    // 记录错误日志
    error(message, error = null) {
        const logEntry = this.createLogEntry('ERROR', message, error);
        this.saveLog(logEntry);
        console.error(logEntry.formatted);
    }

    // 记录警告日志
    warn(message) {
        const logEntry = this.createLogEntry('WARN', message);
        this.saveLog(logEntry);
        console.warn(logEntry.formatted);
    }

    // 记录信息日志
    info(message) {
        const logEntry = this.createLogEntry('INFO', message);
        this.saveLog(logEntry);
        console.log(logEntry.formatted);
    }

    // 创建日志条目
    createLogEntry(level, message, error = null) {
        const timestamp = new Date().toISOString();
        const errorDetails = error ? `\nError: ${error.message}\nStack: ${error.stack}` : '';
        const formatted = `[${timestamp}] ${level}: ${message}${errorDetails}`;
        
        return {
            timestamp,
            level,
            message,
            error,
            formatted
        };
    }

    // 保存日志
    saveLog(logEntry) {
        this.logQueue.push(logEntry);
        if (this.logQueue.length > this.maxLogs) {
            this.logQueue.shift(); // 移除最旧的日志
        }
        
        // 将日志写入本地存储
        try {
            localStorage.setItem('appLogs', JSON.stringify(this.logQueue));
        } catch (e) {
            console.error('无法保存日志到本地存储:', e);
        }
    }

    // 获取所有日志
    getLogs() {
        return this.logQueue;
    }

    // 清除日志
    clearLogs() {
        this.logQueue = [];
        try {
            localStorage.removeItem('appLogs');
        } catch (e) {
            console.error('无法清除本地存储中的日志:', e);
        }
    }

    // 导出日志
    exportLogs() {
        const logsText = this.logQueue.map(log => log.formatted).join('\n');
        const blob = new Blob([logsText], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);
        
        const a = document.createElement('a');
        a.href = url;
        a.download = `logs_${new Date().toISOString().slice(0,10)}.txt`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }
}

// 正确的全局实例创建方式
window.Logger = Logger;
window.logger = new Logger(); 